package leetcode.day_2020_2021_2_1_2021_2_7;

import java.util.Arrays;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
 */
public class LeetCode0034 {
    public static void main(String[] args) {
//        System.out.println(Arrays.toString(searchRange(new int[]{5,7,7,8,8,10}, 8)));
//        System.out.println(Arrays.toString(searchRange(new int[]{5,7,7,8,8,10}, 6)));
        System.out.println(Arrays.toString(searchRange(new int[]{2, 2}, 3)));
    }

    public static int[] searchRange(int[] nums, int target) {
        // 使用二分查找法
        int[] res = new int[2];
        // 查找target第一次出现
        int fisrt = findFirst(nums, target);
        // 查找target第二次出现
        int last = findLast(nums, target);
        res[0] = fisrt;
        res[1] = last;
        return res;
    }

    private static int findLast(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = (left+right) / 2;
            if (nums[mid] == target) {
                left = mid + 1;
            } else if (nums[mid] < target) {
                left = mid+1;
            } else if (nums[mid] > target) {
                right = mid-1;
            }
        }
        if (right < 0 || nums[right] != target) {
            return -1;
        }
        return nums[right]==target ? right : -1;
    }

    private static int findFirst(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = (left+right) / 2;
            if (nums[mid] == target) {
                right = mid-1;
            } else if (nums[mid] < target) {
                left = mid+1;
            } else if (nums[mid] > target) {
                right = mid-1;
            }
        }
        if (left>=nums.length || nums[left]!=target) {
            return -1;
        }
        return nums[left]==target ? left : -1;
    }


}
